import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'

// 数据返回的接口
// 定义请求响应参数，不含data
interface Result {
    status: number;
    message: string
}

// 请求响应参数，包含data
interface ResultData<T = any> extends Result {
    data?: T;
}

// const URL: string =  
enum RequestEnums {
    TIMEOUT = 20000,
    FAIL = 20001, // 请求失败
    SUCCESS = 20000, // 请求成功
}

const config = {
    // 默认地址
    baseURL: 'http://localhost:3000' as string,
    // 设置超时时间
    timeout: RequestEnums.TIMEOUT as number,
}

class RequestHttp {
    // 定义成员变量并指定类型
    service: AxiosInstance;
    public constructor(config: AxiosRequestConfig) {
        // 实例化axios
        this.service = axios.create(config);
        this.service.interceptors.request.use(
            (config: AxiosRequestConfig) => {
                return {
                    ...config,
                }
            },
            (error: AxiosError) => {
                // 请求报错
                Promise.reject(error)
            }
        )

         /**
         * 响应拦截器
         * response -> { 响应拦截器 } -> client
         */
          this.service.interceptors.response.use(
            (response: AxiosResponse) => {
                const { data, config } = response;
                if (data.code && data.code !== RequestEnums.SUCCESS) {
                    // ElMessage.error(data);
                    // console.log(data);
                    return Promise.reject(data);
                }
                return data
            },
            (error: AxiosError) => {
                const { response } = error;})
    }
    // 常用方法封装
    get<T>(url: string, params?: object): Promise<ResultData<T>> {
        return this.service.get(url, { params });
    }
    post<T>(url: string, params?: object): Promise<ResultData<T>> {
        return this.service.post(url, params);
    }
    put<T>(url: string, params?: object): Promise<ResultData<T>> {
        return this.service.put(url, params);
    }
    delete<T>(url: string, params?: object): Promise<ResultData<T>> {
        return this.service.delete(url, { params });
    }
}

export default new RequestHttp(config);
